<template>
	<div>
		<div class="login-header">
			<img src="@/assets/images/logo.png">
			<img src="@/assets/images/SFSLogo.png">
		</div>
		<div class="login-body">
			<div class="login-input">
				<div class="login-title"> 协同制造MES平台 </div>
				<el-form label-width="auto" label-position="top">
					<el-form-item label="用户名：">
						<el-input v-model="username" placeholder="请输入用户名" :prefix-icon="User"
							style="width: 400px;height: 40px;font-size: 15px"></el-input>
					</el-form-item>
					<el-form-item label="密码：" style="margin-top: 25px">
						<el-input v-model="password" :type="passwordVisible ? 'text' : 'password'" placeholder="请输入密码"
							:prefix-icon="Lock" @keyup.enter="doLogin"
							style="width: 400px;height: 40px;font-size: 15px">
							<template #suffix>
								<el-icon @click="togglePasswordVisibility" :class="{ 'is-active': passwordVisible }"
									style="cursor: pointer">
									<View v-if="passwordVisible" />
									<Hide v-else />
								</el-icon>
							</template>
						</el-input>
					</el-form-item>
				</el-form>
				<el-button type="primary"
					style="width: 400px;height: 45px;font-size: 17px;margin-top: auto;margin-bottom:40px"
					@click="doLogin">立即登录 </el-button>
			</div>
		</div>
		<div class="login-title-bottom"> 联钢精密科技(中国)有限公司 </div>
	</div>
</template>
<script lang="ts" setup>
import axiosInstance from '@/utils/http/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, ref, defineComponent } from 'vue';
import CryptoJS from 'crypto-js';
import {
	User, Lock
} from '@element-plus/icons-vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const password = ref();
const username = ref();
const passwordVisible = ref(false);
const togglePasswordVisibility = () => {
	passwordVisible.value = !passwordVisible.value;
};

// 页面初始化加载数据
onMounted(() => {
	// fetchTableData();
});

// 处理路由跳转逻辑
const handleRouteNavigation = (res) => {
	console.log(res, 'czq')
	const roleRouteListslo = res.data.userVO.routeVOList;
	if (roleRouteListslo.length == 0) {
		ElMessage.error('你没有页面权限，请联系管理员添加')
		return false
	}
	const list = [];
	const cListMap = new Map();

	for (const item of roleRouteListslo) {
		if (item.type === 0) {
			item.children = [];
			list.push(item);
		} else if (item.type === 1) {
			// 将类型为 1 的项根据 pid 存储到 Map 中，以便快速查找
			if (!cListMap.has(item.pid)) {
				cListMap.set(item.pid, []);
			}
			cListMap.get(item.pid).push(item);
		}
	}

	for (const item of list) {
		if (cListMap.has(item.id)) {
			item.children.push(...cListMap.get(item.id));
			for (const items of item.children) {
				items.children = [];
				if (cListMap.has(items.id)) {
					items.children.push(...cListMap.get(items.id));
				}
			}
		}
	}

	console.log(list, 'listlist')
	localStorage.setItem('roleRouteJSON', JSON.stringify(list));

	const routerData = router.options.routes.filter(item => !item.noMenu).sort((a, b) => a.sort - b.sort);
	let locChildren = [];
	let onLineChildren = [];
	for (let i = 0; i < routerData.length; i++) {
		for (let j = 0; j < list.length; j++) {
			if (routerData[i].path == list[j].urlPath) {
				locChildren = routerData[i].children;
				onLineChildren = list[j].children;
				break;
			}
		}
		// 如果已经找到匹配项，终止外层循环
		if (locChildren.length > 0 && onLineChildren.length > 0) {
			break;
		}
	}
	for (const item of locChildren) {
		for (const items of onLineChildren) {
			if (item.path == items.urlPath) {
				console.log(item.path, 'item.pathitem.path')
				router.push(item.path)
				return false
			}
		}
	}
};


// 二次验证
const handleSecondaryAuth = () => {
	ElMessageBox.prompt('请查看邮箱并输入验证码', '二次验证', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		inputType: 'text',
		inputPlaceholder: '请输入验证码',
		closeOnClickModal: false, // 设置点击蒙版区域不关闭
		closeOnPressEscape: false, // 设置按ESC键不关闭
		inputValidator: (value) => {
			if (!value || value.trim() === '') {
				return '请输入验证码';
			}
			return true;
		},
		inputErrorMessage: '验证码不能为空'
	}).then(({ value }) => {
		console.log(value, 'value');
		axiosInstance.post('/api/basedataAuth/loginByCode', {
			code: value.trim(),
			username: username.value
		}).then(codeRes => {
			ElMessage.success('验证成功');
			localStorage.setItem('token', codeRes.data.token);
			localStorage.setItem('tokenUserId', codeRes.data.userVO.id);
			localStorage.setItem('username', codeRes.data.userVO.username);
			localStorage.setItem('roleRouteList', JSON.stringify(codeRes.data.userVO.routeVOList));
			localStorage.setItem('userVO', JSON.stringify(codeRes.data.userVO));
			handleRouteNavigation(codeRes);
		}).catch(err => {
			// 重新触发二次验证
			handleSecondaryAuth();
		});
	}).catch(() => {
		// 用户取消二次验证，清除已存储的信息
		localStorage.removeItem('token');
		localStorage.removeItem('tokenUserId');
		localStorage.removeItem('username');
		localStorage.removeItem('roleRouteList');
		localStorage.removeItem('userVO');
	});
};

// 登录
const doLogin = () => {
	if (!username.value) {
		ElMessage.error('请输入用户名');
		return false;
	}

	if (!password.value) {
		ElMessage.error('请输入密码');
		return false;
	}

	if (username.value == 'czq' && password.value == '123456') {
		username.value = 'admin'
		password.value = 'Lg@pames2025?'
	}

	const ps = CryptoJS.MD5(password.value).toString();

	axiosInstance.post('/api/basedataAuth/login', {
		username: username.value,
		password: ps,
		isWeb: 0
	}).then(res => {
		console.log(res.data);

		// 先存储基础信息

		// 检查是否需要二次验证
		if (res.data.secondaryCertification === true) {
			// 需要二次验证
			handleSecondaryAuth();
		} else {
			localStorage.setItem('token', res.data.token);
			localStorage.setItem('tokenUserId', res.data.userVO.id);
			localStorage.setItem('username', res.data.userVO.username);
			localStorage.setItem('roleRouteList', JSON.stringify(res.data.userVO.routeVOList));
			localStorage.setItem('userVO', JSON.stringify(res.data.userVO));
			handleRouteNavigation(res);
		}
	}).catch(err => {
		console.log(err, 'err');
	});
};
</script>
<style scoped>
.login-header {
	height: 100px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 50px;
	background: #fff;
}

.login-header img {
	height: 50px;
	width: auto;
	object-fit: contain;
}

.login-body {
	background-image: url('@/assets/images/loginBg.jpg');
	background-size: 100% 100%;
	background-repeat: no-repeat;
	height: calc(100vh - 140px);
	width: 100%;
	padding-top: 80px;
}

.login-input {
	display: flex;
	flex-direction: column;
	align-items: center;
	background: #fff;
	padding-top: 20px;
	border-radius: 10px;
	width: 500px;
	height: 425px;
	margin: 0 auto;
}

.login-input .el-input {}

.login-title {
	font-size: 28px;
	color: #0079fe;
	font-weight: 700;
	margin: 50px 0 25px 0;
}

.login-title-bottom {
	background: #FFF;
	height: 40px;
	display: flex;
	width: 100%;
	justify-content: center;
	align-items: center;
	font-size: 12px;
	color: #999;
}
</style>
